package de.wepner.texteditor.command;

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

import de.wepner.texteditor.model.EditedFile;
import de.wepner.texteditor.model.EditorData;


/**
 * <a>The command that gets called when the user wants to exit the application,
 * either by clicking on the windows close button, or by selecting the menu item.</p>
 * <p>Before firing the event to close the editor window, this command checks if
 * there are any unsaved changes and asks the user to either save or discard the
 * changes, or to cancel the window closing</p>
 * 
 * @author Richard Wepner
 */
public class ExitCommand extends Command {
    
    private final EditorData data;
    private final Component window;
    
    
    public ExitCommand(EditorData data, Component window) {
        this.data = data;
        this.window = window;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        EditedFile file = this.data.getEditedFile();
        final boolean doClose;
        if (file != null && file.isDirty()) {
            int dialogResult = JOptionPane.showConfirmDialog(this.window,
                    "Do you want to save your changes before closing the editor?", "Unsaved data",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
            switch (dialogResult) {
                case JOptionPane.YES_OPTION:
                    this.data.commands.getCommand(EditorData.SAVE_FILE_COMMAND).actionPerformed(e);
                    doClose = !file.isDirty();
                    break;
                case JOptionPane.NO_OPTION:
                    doClose = true;
                    break;
                default:
                    doClose = false;
                    break;
            }
        } else {
            doClose = true;
        }
        
        if (doClose) {
            this.data.closeEditor.fireEvent(Integer.valueOf(0));
        }
    }
}
